﻿Imports System.Runtime.InteropServices
Imports System.Text

Delegate Sub SetActivated(ByVal value As Boolean)
Delegate Sub SetText(ByVal value As String)

Public Class WindowControl
    Dim Handle As IntPtr

    Dim ForegroundHandle As IntPtr

    Public Property WinHandle As IntPtr
        Get
            Return Handle
        End Get
        Set(ByVal value As IntPtr)
            Handle = value
        End Set
    End Property

    Private Sub SetActivated(ByVal value As Boolean)
        If value Then
            Me.Background = New LinearGradientBrush(Color.FromArgb(255, 40, 40, 40), Colors.Black, 270)
        Else
            Me.Background = New LinearGradientBrush(Color.FromArgb(255, 40, 40, 40), Colors.Black, 90)
        End If
    End Sub

    Private Sub SetText(ByVal value As String)
        LabelText.Content = value
    End Sub

    Private Sub Update()
        Dim WindowText As New StringBuilder(255)

        GetWindowText(Handle, WindowText, 255)
        Dim sa As New SetActivated(AddressOf SetActivated)
        Dim st As New SetText(AddressOf SetText)
        Me.Dispatcher.Invoke(sa, ForegroundHandle = Handle)
        LabelText.Dispatcher.Invoke(st, WindowText.ToString)

        GetWindowText(GetForegroundWindow, WindowText, 255)

        If Not WindowText.ToString = "WinPanel" Then
            ForegroundHandle = GetForegroundWindow
        End If
    End Sub

    Private Sub UpdateLoop()
        Do
            Update()
            System.Threading.Thread.Sleep(100)
        Loop
    End Sub

    Private Sub UserControl_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Dim t As New System.Threading.Thread(AddressOf UpdateLoop)
        t.Start()
    End Sub

    Private Sub UserControl_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles MyBase.MouseLeftButtonUp
        If Not ForegroundHandle = Handle Then
            If IsWindowMinimized(Handle) Then
                ShowWindow(Handle, 9)
            Else
                SetForegroundWindow(Handle)
            End If
        Else
            ShowWindow(Handle, 6)
        End If
    End Sub
End Class
